package utilities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class IncomingCallReciever extends BroadcastReceiver {

//	private Context mContext;
//	private Intent mIntent;
	private boolean isPhoneCalling = false;
	private String TAG="mm-sv";

	@Override
	public void onReceive(Context context, Intent intent) {
//		mContext = context;
//		mIntent = intent;
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		int events = PhoneStateListener.LISTEN_CALL_STATE;
		tm.listen(phoneStateListener, events);
	}

	private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
		
		@Override
	    public void onCallStateChanged(int state, String incomingNumber) {

	        if (TelephonyManager.CALL_STATE_RINGING == state) {
	            // phone ringing
	            Log.i(TAG, "RINGING, number: " + incomingNumber);
	        }

	        if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
	            // active
	            Log.i(TAG, "OFFHOOK");

	            isPhoneCalling = true;
	        }

	        if (TelephonyManager.CALL_STATE_IDLE == state) {
	            // run when class initial and phone call ended,
	            // need detect flag from CALL_STATE_OFFHOOK
	            Log.i(TAG, "IDLE");

	            if (isPhoneCalling) {

	                Log.i(TAG, "TERMINO LA LLAMADA =D");
//
//	                // restart call application
//	                Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
//	                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//	                        | Intent.FLAG_ACTIVITY_CLEAR_TOP
//	                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//	                startActivity(i);

	                isPhoneCalling = false;
	            }

	        }


	}
		
	};
}

